<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\common\model;
use think\Model;

class UserFavorite extends Model
{
    protected $autoWriteTimestamp = true;

    /**
     * 关联买家用户
     */
    public function user()
    {
        return $this->belongsTo('PersonalUser', 'user_id');
    }

    /**
     * 关联商品
     */
    public function goods()
    {
        return $this->belongsTo('Goods', 'relation_id')->where('type', 1);
    }

    /**
     * 获取用户是否已收藏商品
     * 
     * @param int $user_id 买家ID
     * @param int $goods_id 商品ID
     * @return bool
     */
    public static function isGoodsFavorited($user_id, $goods_id)
    {
        if (empty($user_id) || empty($goods_id)) {
            return false;
        }

        return self::where([
            'user_id'     => $user_id,
            'relation_id' => $goods_id,
            'type'        => 1
        ])->cache(30)->count() > 0;
    }

    /**
     * 添加或取消收藏
     * 
     * @param int $user_id 买家ID
     * @param int $relation_id 关联ID(商品ID)
     * @param int $type 类型(1=商品)
     * @return array
     */
    public static function toggleFavorite($user_id, $relation_id, $type)
    {
        if (empty($user_id) || empty($relation_id) || !in_array($type, [1, 2])) {
            return [
                'code' => 0,
                'msg'  => '参数错误'
            ];
        }

        $where = [
            'user_id'     => $user_id,
            'relation_id' => $relation_id,
            'type'        => $type
        ];

        $exists = self::where($where)->find();

        if ($exists) {
            // 已存在,则取消收藏
            $exists->delete();
            return [
                'code'         => 1,
                'msg'          => $type == 1 ? '取消收藏成功' : '取消关注成功',
                'is_favorited' => false
            ];
        } else {
            // 不存在,则添加收藏
            self::create($where);
            return [
                'code'         => 1,
                'msg'          => $type == 1 ? '收藏成功' : '关注成功',
                'is_favorited' => true
            ];
        }
    }
}